package com.example.esp8266.activity.wifi;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.example.esp8266.R;
import com.example.esp8266.activity.MainActivity;
import java.util.ArrayList;
import java.util.List;

public class WifiActivity extends AppCompatActivity implements View.OnClickListener {
    private static String TAG = WifiActivity.class.getSimpleName();
    private WifiReceiver mReceiver;
    private Button btnWifiOpen, btnWifiClose, btnWifiScan;
    private ListView listView;
    private ProgressBar progressBar;
    private WifiManager mWifiManager;
    private List<ScanResult> mWifiList;
    private List<WifiConfiguration> mWifiConfiguration;
    private WifiAdapter mAdapter;
    private List<ScanResult> mList;
    private String mWifiState = "未开启";
    private static final int WRITE_COARSE_LOCATION_REQUEST_CODE = 0;//定位权限
//    -------WiFi 连接 ---------
//    private static final String TAG1 = WifiActivity.class.getSimpleName();
    private ScanResult mScanResult;
    private String mWifiApState = "未连接";

    private NetState netState;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi);
        initView();
        mWifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        //TODO 测试
//        //1.
//        try {
//            String ip3 = IPUtils.getIp(this);
//            Log.e(TAG, "ip3 " + ip3);
//        } catch (SocketException e) {
//            e.printStackTrace();
//        }
//        //2.
//        try {
//            IpUtil.getIpInLAN();
//            IpUtil.getIpInLAN2();
//        } catch (SocketException e) {
//            e.printStackTrace();
//        }
        System.out.println("路由器ip：" + WifiUtil.getWifiRouteIPAddress(this));
        if (Build.VERSION.SDK_INT >= 23) {  //开启 动态定位
            showPermissions();
        }
        //注册广播
        netState = new NetState();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        this.registerReceiver(netState, filter);
    }

    private void initView() {
        btnWifiOpen = findViewById(R.id.wifi_open);
        btnWifiClose = findViewById(R.id.wifi_close);
        btnWifiScan = findViewById(R.id.wifi_scan);
        progressBar = findViewById(R.id.progressBar);
        listView = findViewById(R.id.wifi_list);
        mList = new ArrayList<>();
        mAdapter = new WifiAdapter(this, mList);
        listView.setAdapter(mAdapter);
        btnWifiOpen.setOnClickListener(this);
        btnWifiClose.setOnClickListener(this);
        btnWifiScan.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mScanResult = mList.get(position);
                connect();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wifi_open: //打开WiFi
                if (!mWifiManager.isWifiEnabled()) { //判断状态
                    mWifiManager.setWifiEnabled(true);
                }
                break;
            case R.id.wifi_close: //关闭WiFi
                if (mWifiManager.isWifiEnabled()) {
                    mWifiManager.setWifiEnabled(false);
                }
                break;
            case R.id.wifi_scan: // 搜索WiFi
                if (mWifiManager.isWifiEnabled()) {
                    progressBar.setVisibility(View.VISIBLE);// 加载进度条
                    startScan();
                    mAdapter.setData(null);
                } else {
                    Toast.makeText(this, "WiFi没有开启", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册WiFi状态广播
        registerReceiver();
        if (mWifiManager.isWifiEnabled()) {
            progressBar.setVisibility(View.VISIBLE);
            startScan();
            mAdapter.setData(null);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.unregisterReceiver(mReceiver);
    }
    public void startScan() {
        mWifiManager.startScan();
    }

// 获取WiFi扫码结果
    private void getWiFiList() {
        //得到扫描结果
        List<ScanResult> results = mWifiManager.getScanResults();
        // 得到配置好的网络连接
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();

        if (results == null) {
            int wifiState = mWifiManager.getWifiState();
            switch (wifiState) {
                case WifiManager.WIFI_STATE_ENABLED:
                    Toast.makeText(this, "当前区域没有无线网络", Toast.LENGTH_SHORT).show();
                    break;
                case WifiManager.WIFI_STATE_ENABLING:
                    Toast.makeText(this, "wifi正在开启,请稍后扫描", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    Toast.makeText(this, "WiFi没有开启", Toast.LENGTH_SHORT).show();
                    break;
            }
        } else {
            mWifiList = new ArrayList();
            for (ScanResult result : results) {
                if (result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]")) {
                    continue;
                }
                boolean found = false;
                for (ScanResult item : mWifiList) {
                    if (item.SSID.equals(result.SSID) && item.capabilities.equals(result.capabilities)) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    mWifiList.add(result);
                }
            }
        }

        if (mWifiList != null && mWifiList.size() > 0) {
            for (ScanResult result : mWifiList) {

                int nSigLevel = WifiManager.calculateSignalLevel(result.level, 4);
                Log.e(TAG, "SSID : "
                        + result.SSID + " BSSID : "
                        + result.BSSID + " RSSI : " + nSigLevel);
                Log.e(TAG, "capabilities : " + result.capabilities);
            }
            //显示列表
            mAdapter.setData(mWifiList);
        }
    }
    private class WifiReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
                switch (wifistate) {
                    case WifiManager.WIFI_STATE_DISABLED:
                        //wifi已关闭
                        Log.e(TAG, "WIFI 断开");
                        invalidateOptionsMenu();
                        mWifiState="未开启";
                        btnWifiOpen.setText("打开WiFi");
                        btnWifiClose.setText("WiFi已关闭");
                        break;
                    case WifiManager.WIFI_STATE_ENABLED:
                        //wifi已打开
                        Log.e(TAG, "WIFI 开启");
                        mWifiState="已开启";
                        btnWifiOpen.setText("WiFi已打开");
                        btnWifiClose.setText("关闭WiFi");
                        invalidateOptionsMenu();
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        //wifi正在打开
                        Log.e(TAG, "WIFI 开启中...");
                        mWifiState="开启中...";
                        break;
                    default:
                        break;
                }
            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {
                progressBar.setVisibility(View.GONE);
                boolean isScanned = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false);
                Log.e(TAG, "isScanned : " + isScanned);
                getWiFiList();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netState != null) {  // 取消注册 BroadcastReceiver
            unregisterReceiver(netState);
        }
    }
    private void registerReceiver() {
        mReceiver = new WifiReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        this.registerReceiver(mReceiver, filter);
    }
    public void showPermissions() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(WifiActivity.this, new String[]{
                    Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE
            }, WRITE_COARSE_LOCATION_REQUEST_CODE);
        }

    }

    // Android 6.0 以上的版本 申请定位权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case WRITE_COARSE_LOCATION_REQUEST_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(this, "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    //  连接WiFi 方法
    private void connect() {
        if (mScanResult != null) {
            final int type = WifiUtil.getEncryptedType(mScanResult.capabilities);
            if (WifiUtil.isEncrypted(mScanResult.capabilities)) {//加密，需要密码
                final EditText editText = new EditText(WifiActivity.this);
                final TextView textView = new TextView(WifiActivity.this);
                textView.setText("12345678");
                textView.setTextSize(20);
                new AlertDialog.Builder(WifiActivity.this)
                        .setTitle("Wifi密码：")
                        .setIcon(R.drawable.info)
                        .setView(textView)
                        .setPositiveButton("连接", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.e(TAG, "密码 :" + editText.getText());
                                String password = textView.getText().toString().trim();
                                if (!TextUtils.isEmpty(password)) {
                                    connectWifi(mScanResult.SSID, password, type);
                                    Intent intent1 = new Intent(WifiActivity.this,MainActivity.class);
                                    startActivity(intent1);
                                } else {
                                    Toast.makeText(WifiActivity.this, "请确认密码", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("罢了", null)
                        .show();
            } else {
                connectWifi(mScanResult.SSID, null, type);
            }
        }
    }

    /**
     * 连接wifi 参数：wifi的ssid及wifi的密码
     */
    private void connectWifi(final String ssid, final String pwd, int type) {
        Log.i(TAG, "ssid : " + ssid + " pwd : " + pwd + " type : " + type);
        mWifiManager.disconnect();
        addNetwork(CreateWifiInfo(ssid, pwd, type));
    }

    /**
     * 添加一个网络并连接传入参数：WIFI发生配置类WifiConfiguration
     */
    public void addNetwork(WifiConfiguration wcg) {
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean enable = mWifiManager.enableNetwork(wcgID, true);
        Log.e(TAG, "wcgID :  " + wcgID + "  enable : " + enable);
    }

    // 创建 WiFi 信息
    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        if (Type == WifiUtil.SECURITY_NONE) {// WIFICIPHER_NOPASS
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiUtil.SECURITY_WEP) {// WIFICIPHER_WEP
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiUtil.SECURITY_WPA) {// WIFICIPHER_WPA
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            //config.allowedKeyManagement.set(4);//WPA2_PSK
            config.status = WifiConfiguration.Status.ENABLED;
        }

        return config;
    }
    public WifiInfo getCurrentWifiInfo() {
        return mWifiManager.getConnectionInfo();
    }

    private WifiConfiguration IsExsits(String SSID) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        if (existingConfigs != null) {
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                    return existingConfig;
                }
            }
        }
        return null;
    }
//--------- 判断WiFi的连接状态  -------
    public class NetState extends BroadcastReceiver {
    @SuppressLint("SetTextI18n")
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null) return;
        String action = intent.getAction();
        if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
            //主要用来判断密码错误,认证失败
            int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 0);

            if (WifiManager.ERROR_AUTHENTICATING == error) {
                //密码错误,认证失败
                Log.e(TAG, "密码错误或认证失败");
            }
        } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
            NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            if (info == null) return;
            Log.e(TAG, "State： " + info.getState());
//                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
//                    Log.e(TAG, "连接已断开");
//                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
//                } else {
            NetworkInfo.DetailedState state = info.getDetailedState();
            //Log.e(TAG, "DetailedState ： "+state.toString());
            if (state == NetworkInfo.DetailedState.CONNECTING) {
                Log.e(TAG, "WIFI连接中...");

            } else if (state == NetworkInfo.DetailedState.AUTHENTICATING) {
                Log.e(TAG, "WIFI正在验证身份信息...");
            } else if (state == NetworkInfo.DetailedState.OBTAINING_IPADDR) {
                Log.e(TAG, "WIFI正在获取IP地址...");
            } else if (state == NetworkInfo.DetailedState.CONNECTED) {
                Log.e(TAG, "WIFI连接成功");
                WifiInfo wifiInfo = getCurrentWifiInfo();
                Toast.makeText(WifiActivity.this, "已连接到WIFI : " + wifiInfo.getSSID(), Toast.LENGTH_SHORT).show();
                invalidateOptionsMenu();
                mWifiApState = "已连接";
            } else if (state == NetworkInfo.DetailedState.DISCONNECTED) {
                Log.e(TAG, "WIFI连接断开");
                Toast.makeText(WifiActivity.this, "WIFI连接断开", Toast.LENGTH_SHORT).show();
                mWifiApState = "未连接";
                invalidateOptionsMenu();
            } else if (state == NetworkInfo.DetailedState.FAILED) {
                Log.e(TAG, "WIFI连接失败");
                Toast.makeText(WifiActivity.this, "WIFI连接失败", Toast.LENGTH_SHORT).show();
                invalidateOptionsMenu();
            } else if (state == NetworkInfo.DetailedState.SCANNING) {
                Log.i(TAG, "WIFI扫描中...");
            } else if (state == NetworkInfo.DetailedState.BLOCKED) {
                Log.i(TAG, "WIFI访问被阻止");
                Toast.makeText(WifiActivity.this, "WIFI访问被阻止", Toast.LENGTH_SHORT).show();
            } else if (state == NetworkInfo.DetailedState.VERIFYING_POOR_LINK) {
                Log.i(TAG, "WIFI链路连通性差");
            } else if (state == NetworkInfo.DetailedState.CAPTIVE_PORTAL_CHECK) {
                Log.i(TAG, "WIFI检查网络是否是受控门户");
            }
            //}
        }
    }
}


}
